// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

#include <PySelectionVariableSummary.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <Py2and3Support.h>

// ****************************************************************************
// Module: PySelectionVariableSummary
//
// Purpose:
//   Contains a summary of a variable used in a selection
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

//
// This struct contains the Python type information and a SelectionVariableSummary.
//
struct SelectionVariableSummaryObject
{
    PyObject_HEAD
    SelectionVariableSummary *data;
    bool        owns;
    PyObject   *parent;
};

//
// Internal prototypes
//
static PyObject *NewSelectionVariableSummary(int);
std::string
PySelectionVariableSummary_ToString(const SelectionVariableSummary *atts, const char *prefix, const bool forLogging)
{
    std::string str;
    char tmpStr[1000];

    snprintf(tmpStr, 1000, "%sname = \"%s\"\n", prefix, atts->GetName().c_str());
    str += tmpStr;
    snprintf(tmpStr, 1000, "%sminimum = %g\n", prefix, atts->GetMinimum());
    str += tmpStr;
    snprintf(tmpStr, 1000, "%smaximum = %g\n", prefix, atts->GetMaximum());
    str += tmpStr;
    {   const double *histogram = atts->GetHistogram();
        snprintf(tmpStr, 1000, "%shistogram = (", prefix);
        str += tmpStr;
        for(int i = 0; i < 256; ++i)
        {
            snprintf(tmpStr, 1000, "%g", histogram[i]);
            str += tmpStr;
            if(i < 255)
            {
                snprintf(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        snprintf(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    return str;
}

static PyObject *
SelectionVariableSummary_Notify(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;
    obj->data->Notify();
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionVariableSummary_SetName(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged as first member of a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyUnicode_Check(packaged_args))
            args = packaged_args;
    }

    if (!PyUnicode_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a unicode string");
    }

    char const *val = PyUnicode_AsUTF8(args);
    std::string cval = std::string(val);

    if (val == 0 && PyErr_Occurred())
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as utf8 string");
    }

    Py_XDECREF(packaged_args);

    // Set the name in the object.
    obj->data->SetName(cval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionVariableSummary_GetName(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;
    PyObject *retval = PyString_FromString(obj->data->GetName().c_str());
    return retval;
}

/*static*/ PyObject *
SelectionVariableSummary_SetMinimum(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged into a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyNumber_Check(packaged_args))
            args = packaged_args;
    }

    if (PySequence_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "expecting a single number arg");
    }

    if (!PyNumber_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a number type");
    }

    double val = PyFloat_AsDouble(args);
    double cval = double(val);

    if (val == -1 && PyErr_Occurred())
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ double");
    }
    if (fabs(double(val))>1.5E-7 && fabs((double(double(cval))-double(val))/double(val))>1.5E-7)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_ValueError, "arg not interpretable as C++ double");
    }

    Py_XDECREF(packaged_args);

    // Set the minimum in the object.
    obj->data->SetMinimum(cval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionVariableSummary_GetMinimum(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;
    PyObject *retval = PyFloat_FromDouble(obj->data->GetMinimum());
    return retval;
}

/*static*/ PyObject *
SelectionVariableSummary_SetMaximum(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged into a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyNumber_Check(packaged_args))
            args = packaged_args;
    }

    if (PySequence_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "expecting a single number arg");
    }

    if (!PyNumber_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a number type");
    }

    double val = PyFloat_AsDouble(args);
    double cval = double(val);

    if (val == -1 && PyErr_Occurred())
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ double");
    }
    if (fabs(double(val))>1.5E-7 && fabs((double(double(cval))-double(val))/double(val))>1.5E-7)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_ValueError, "arg not interpretable as C++ double");
    }

    Py_XDECREF(packaged_args);

    // Set the maximum in the object.
    obj->data->SetMaximum(cval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionVariableSummary_GetMaximum(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;
    PyObject *retval = PyFloat_FromDouble(obj->data->GetMaximum());
    return retval;
}

/*static*/ PyObject *
SelectionVariableSummary_SetHistogram(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;

    PyObject *packaged_args = 0;
    double *vals = obj->data->GetHistogram();

    if (!PySequence_Check(args) || PyUnicode_Check(args))
        return PyErr_Format(PyExc_TypeError, "Expecting a sequence of numeric args");

    // break open args seq. if we think it matches this API's needs
    if (PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PySequence_Check(packaged_args) && !PyUnicode_Check(packaged_args) &&
            PySequence_Size(packaged_args) == 256)
            args = packaged_args;
    }

    if (PySequence_Size(args) != 256)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "Expecting 256 numeric args");
    }

    for (Py_ssize_t i = 0; i < PySequence_Size(args); i++)
    {
        PyObject *item = PySequence_GetItem(args, i);

        if (!PyNumber_Check(item))
        {
            Py_DECREF(item);
            Py_XDECREF(packaged_args);
            return PyErr_Format(PyExc_TypeError, "arg %d is not a number type", (int) i);
        }

        double val = PyFloat_AsDouble(item);
        double cval = double(val);

        if (val == -1 && PyErr_Occurred())
        {
            Py_XDECREF(packaged_args);
            Py_DECREF(item);
            PyErr_Clear();
            return PyErr_Format(PyExc_TypeError, "arg %d not interpretable as C++ double", (int) i);
        }
        if (fabs(double(val))>1.5E-7 && fabs((double(double(cval))-double(val))/double(val))>1.5E-7)
        {
            Py_XDECREF(packaged_args);
            Py_DECREF(item);
            return PyErr_Format(PyExc_ValueError, "arg %d not interpretable as C++ double", (int) i);
        }
        Py_DECREF(item);

        vals[i] = cval;
    }

    Py_XDECREF(packaged_args);

    // Mark the histogram in the object as modified.
    obj->data->SelectHistogram();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
SelectionVariableSummary_GetHistogram(PyObject *self, PyObject *args)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)self;
    // Allocate a tuple the with enough entries to hold the histogram.
    PyObject *retval = PyTuple_New(256);
    const double *histogram = obj->data->GetHistogram();
    for(int i = 0; i < 256; ++i)
        PyTuple_SET_ITEM(retval, i, PyFloat_FromDouble(histogram[i]));
    return retval;
}



PyMethodDef PySelectionVariableSummary_methods[SELECTIONVARIABLESUMMARY_NMETH] = {
    {"Notify", SelectionVariableSummary_Notify, METH_VARARGS},
    {"SetName", SelectionVariableSummary_SetName, METH_VARARGS},
    {"GetName", SelectionVariableSummary_GetName, METH_VARARGS},
    {"SetMinimum", SelectionVariableSummary_SetMinimum, METH_VARARGS},
    {"GetMinimum", SelectionVariableSummary_GetMinimum, METH_VARARGS},
    {"SetMaximum", SelectionVariableSummary_SetMaximum, METH_VARARGS},
    {"GetMaximum", SelectionVariableSummary_GetMaximum, METH_VARARGS},
    {"SetHistogram", SelectionVariableSummary_SetHistogram, METH_VARARGS},
    {"GetHistogram", SelectionVariableSummary_GetHistogram, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

static void
SelectionVariableSummary_dealloc(PyObject *v)
{
   SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)v;
   if(obj->parent != 0)
       Py_DECREF(obj->parent);
   if(obj->owns)
       delete obj->data;
}

static PyObject *SelectionVariableSummary_richcompare(PyObject *self, PyObject *other, int op);
PyObject *
PySelectionVariableSummary_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "name") == 0)
        return SelectionVariableSummary_GetName(self, NULL);
    if(strcmp(name, "minimum") == 0)
        return SelectionVariableSummary_GetMinimum(self, NULL);
    if(strcmp(name, "maximum") == 0)
        return SelectionVariableSummary_GetMaximum(self, NULL);
    if(strcmp(name, "histogram") == 0)
        return SelectionVariableSummary_GetHistogram(self, NULL);


    // Add a __dict__ answer so that dir() works
    if (!strcmp(name, "__dict__"))
    {
        PyObject *result = PyDict_New();
        for (int i = 0; PySelectionVariableSummary_methods[i].ml_meth; i++)
            PyDict_SetItem(result,
                PyString_FromString(PySelectionVariableSummary_methods[i].ml_name),
                PyString_FromString(PySelectionVariableSummary_methods[i].ml_name));
        return result;
    }

    return Py_FindMethod(PySelectionVariableSummary_methods, self, name);
}

int
PySelectionVariableSummary_setattr(PyObject *self, char *name, PyObject *args)
{
    PyObject NULL_PY_OBJ;
    PyObject *obj = &NULL_PY_OBJ;

    if(strcmp(name, "name") == 0)
        obj = SelectionVariableSummary_SetName(self, args);
    else if(strcmp(name, "minimum") == 0)
        obj = SelectionVariableSummary_SetMinimum(self, args);
    else if(strcmp(name, "maximum") == 0)
        obj = SelectionVariableSummary_SetMaximum(self, args);
    else if(strcmp(name, "histogram") == 0)
        obj = SelectionVariableSummary_SetHistogram(self, args);

    if (obj != NULL && obj != &NULL_PY_OBJ)
        Py_DECREF(obj);

    if (obj == &NULL_PY_OBJ)
    {
        obj = NULL;
        PyErr_Format(PyExc_NameError, "name '%s' is not defined", name);
    }
    else if (obj == NULL && !PyErr_Occurred())
        PyErr_Format(PyExc_RuntimeError, "unknown problem with '%s'", name);

    return (obj != NULL) ? 0 : -1;
}

static int
SelectionVariableSummary_print(PyObject *v, FILE *fp, int flags)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)v;
    fprintf(fp, "%s", PySelectionVariableSummary_ToString(obj->data, "",false).c_str());
    return 0;
}

PyObject *
SelectionVariableSummary_str(PyObject *v)
{
    SelectionVariableSummaryObject *obj = (SelectionVariableSummaryObject *)v;
    return PyString_FromString(PySelectionVariableSummary_ToString(obj->data,"", false).c_str());
}

//
// The doc string for the class.
//
#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
static const char *SelectionVariableSummary_Purpose = "Contains a summary of a variable used in a selection";
#else
static char *SelectionVariableSummary_Purpose = "Contains a summary of a variable used in a selection";
#endif

//
// Python Type Struct Def Macro from Py2and3Support.h
//
//         VISIT_PY_TYPE_OBJ( VPY_TYPE,
//                            VPY_NAME,
//                            VPY_OBJECT,
//                            VPY_DEALLOC,
//                            VPY_PRINT,
//                            VPY_GETATTR,
//                            VPY_SETATTR,
//                            VPY_STR,
//                            VPY_PURPOSE,
//                            VPY_RICHCOMP,
//                            VPY_AS_NUMBER)

//
// The type description structure
//

VISIT_PY_TYPE_OBJ(SelectionVariableSummaryType,         \
                  "SelectionVariableSummary",           \
                  SelectionVariableSummaryObject,       \
                  SelectionVariableSummary_dealloc,     \
                  SelectionVariableSummary_print,       \
                  PySelectionVariableSummary_getattr,   \
                  PySelectionVariableSummary_setattr,   \
                  SelectionVariableSummary_str,         \
                  SelectionVariableSummary_Purpose,     \
                  SelectionVariableSummary_richcompare, \
                  0); /* as_number*/

//
// Helper function for comparing.
//
static PyObject *
SelectionVariableSummary_richcompare(PyObject *self, PyObject *other, int op)
{
    // only compare against the same type 
    if ( Py_TYPE(self) != &SelectionVariableSummaryType
         || Py_TYPE(other) != &SelectionVariableSummaryType)
    {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    PyObject *res = NULL;
    SelectionVariableSummary *a = ((SelectionVariableSummaryObject *)self)->data;
    SelectionVariableSummary *b = ((SelectionVariableSummaryObject *)other)->data;

    switch (op)
    {
       case Py_EQ:
           res = (*a == *b) ? Py_True : Py_False;
           break;
       case Py_NE:
           res = (*a != *b) ? Py_True : Py_False;
           break;
       default:
           res = Py_NotImplemented;
           break;
    }

    Py_INCREF(res);
    return res;
}

//
// Helper functions for object allocation.
//

static SelectionVariableSummary *defaultAtts = 0;
static SelectionVariableSummary *currentAtts = 0;

static PyObject *
NewSelectionVariableSummary(int useCurrent)
{
    SelectionVariableSummaryObject *newObject;
    newObject = PyObject_NEW(SelectionVariableSummaryObject, &SelectionVariableSummaryType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new SelectionVariableSummary(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new SelectionVariableSummary(*defaultAtts);
    else
        newObject->data = new SelectionVariableSummary;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapSelectionVariableSummary(const SelectionVariableSummary *attr)
{
    SelectionVariableSummaryObject *newObject;
    newObject = PyObject_NEW(SelectionVariableSummaryObject, &SelectionVariableSummaryType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (SelectionVariableSummary *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

///////////////////////////////////////////////////////////////////////////////
//
// Interface that is exposed to the VisIt module.
//
///////////////////////////////////////////////////////////////////////////////

PyObject *
SelectionVariableSummary_new(PyObject *self, PyObject *args)
{
    int useCurrent = 0;
    if (!PyArg_ParseTuple(args, "i", &useCurrent))
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        else
            PyErr_Clear();
    }

    return (PyObject *)NewSelectionVariableSummary(useCurrent);
}

//
// Plugin method table. These methods are added to the visitmodule's methods.
//
static PyMethodDef SelectionVariableSummaryMethods[] = {
    {"SelectionVariableSummary", SelectionVariableSummary_new, METH_VARARGS},
    {NULL,      NULL}        /* Sentinel */
};

static Observer *SelectionVariableSummaryObserver = 0;

std::string
PySelectionVariableSummary_GetLogString()
{
    std::string s("SelectionVariableSummary = SelectionVariableSummary()\n");
    if(currentAtts != 0)
        s += PySelectionVariableSummary_ToString(currentAtts, "SelectionVariableSummary.", true);
    return s;
}

static void
PySelectionVariableSummary_CallLogRoutine(Subject *subj, void *data)
{
    typedef void (*logCallback)(const std::string &);
    logCallback cb = (logCallback)data;

    if(cb != 0)
    {
        std::string s("SelectionVariableSummary = SelectionVariableSummary()\n");
        s += PySelectionVariableSummary_ToString(currentAtts, "SelectionVariableSummary.", true);
        cb(s);
    }
}

void
PySelectionVariableSummary_StartUp(SelectionVariableSummary *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PySelectionVariableSummary_SetDefaults(subj);

    //
    // Create the observer that will be notified when the attributes change.
    //
    if(SelectionVariableSummaryObserver == 0)
    {
        SelectionVariableSummaryObserver = new ObserverToCallback(subj,
            PySelectionVariableSummary_CallLogRoutine, (void *)data);
    }

}

void
PySelectionVariableSummary_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete SelectionVariableSummaryObserver;
    SelectionVariableSummaryObserver = 0;
}

PyMethodDef *
PySelectionVariableSummary_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return SelectionVariableSummaryMethods;
}

bool
PySelectionVariableSummary_Check(PyObject *obj)
{
    return (obj->ob_type == &SelectionVariableSummaryType);
}

SelectionVariableSummary *
PySelectionVariableSummary_FromPyObject(PyObject *obj)
{
    SelectionVariableSummaryObject *obj2 = (SelectionVariableSummaryObject *)obj;
    return obj2->data;
}

PyObject *
PySelectionVariableSummary_New()
{
    return NewSelectionVariableSummary(0);
}

PyObject *
PySelectionVariableSummary_Wrap(const SelectionVariableSummary *attr)
{
    return WrapSelectionVariableSummary(attr);
}

void
PySelectionVariableSummary_SetParent(PyObject *obj, PyObject *parent)
{
    SelectionVariableSummaryObject *obj2 = (SelectionVariableSummaryObject *)obj;
    obj2->parent = parent;
}

void
PySelectionVariableSummary_SetDefaults(const SelectionVariableSummary *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new SelectionVariableSummary(*atts);
}

